package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    @Autowired
    private DeptService deptService;


    @RequestMapping(value = "/list",name = "展示部门列表数据")
    public String findAll(@RequestParam(name="page",defaultValue = "1") Integer pageNum,
                         @RequestParam(name="pageSize",defaultValue = "10") Integer pageSize){
        PageInfo<Dept> pageInfo = deptService.findPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转到新增部门的页面")
    public String toAdd( ){
//        查询当前登录人企业的所有部门，放入到request中再跳转页面
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name = "保存部门方法")
    public String save(Dept dept){
//        新增 id上是没有值的
//        修改 id是有值的

        if(dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }

        if(StringUtils.isEmpty(dept.getId())){ //ID为空 新增
            dept.setId(UUID.randomUUID().toString());
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);
        }else{
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do"; //重定向到部门列表中
    }

    @RequestMapping(value = "/toUpdate",name = "进入到部门编辑页面")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);

        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

        request.setAttribute("dept",dept);
        return "system/dept/dept-add";
    }
    @RequestMapping(value = "/delete",name = "删除部门数据")
    public String delete(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }


}
